package logic

import (
	"context"
	"fmt"
	"strconv"
	"time"
	"xialou_platform/app/errorx"
	"xialou_platform/app/joinpay"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"

	"xialou_platform/services/wallet/rpc/internal/svc"
	"xialou_platform/services/wallet/rpc/walletClient"

	"github.com/zeromicro/go-zero/core/logx"
)

type WithdrawalPaymentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWithdrawalPaymentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WithdrawalPaymentLogic {
	return &WithdrawalPaymentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 提现打款
func (l *WithdrawalPaymentLogic) WithdrawalPayment(in *walletClient.WithdrawalPaymentReq) (*walletClient.EmptyBody, error) {

	withdrawal, err := l.svcCtx.WalletWithdrawalModel.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, err
	}

	// 未打款
	if withdrawal.Status == 0 {

		useAbleSettAmount, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", float64(withdrawal.Amount)/100), 64)

		accountBalanceResp, err := joinpay.AccountBalanceQuery(in.JoinPayMerchantKey, joinpay.AccountBalanceReq{
			UserNo: in.JoinPayUserNo,
		})
		if err != nil {
			return nil, err
		}
		if accountBalanceResp.StatusCode == 2001 {
			if accountBalanceResp.Data.UseAbleSettAmount < useAbleSettAmount {
				return nil, errorx.NewDefaultError(fmt.Sprintf("当前商户金额：%v,不足以支付，请到汇管家出金，或者到微信支付提现后再到汇管家出金",
					accountBalanceResp.Data.UseAbleSettAmount))
			}
		} else {
			return nil, errorx.NewDefaultError(accountBalanceResp.Message)
		}

		walletInfo, err := l.svcCtx.WalletModel.FindOneBySourceId(l.ctx, withdrawal.SourceId)
		if err != nil {
			return nil, err
		}

		payDesc := "下楼科技"
		switch walletInfo.SourceType {
		case 1:
			payDesc = "下楼销氪提现"
		case 2:
			payDesc = "下楼休闲吧商家提现"

		}

		singlePayResp, err := joinpay.SinglePay(in.JoinPayMerchantKey, joinpay.SinglePayReq{
			UserNo:                in.JoinPayUserNo,
			ProductCode:           "BANK_PAY_DAILY_ORDER",
			RequestTime:           tools.TimeUnixShowLayoutString(time.Now().Unix()),
			MerchantOrderNo:       respx.IDFrom(withdrawal.Id).ToString(),
			ReceiverAccountNoEnc:  walletInfo.BankNumber,
			ReceiverNameEnc:       walletInfo.AccountName,
			ReceiverAccountType:   "201",
			ReceiverBankChannelNo: "",
			PaidAmount:            fmt.Sprintf("%.2f", float64(withdrawal.Amount-50)/100), //打款前扣除5毛钱手续费
			Currency:              "201",
			IsChecked:             "202",
			PaidDesc:              payDesc,
			PaidUse:               "201",
			CallbackUrl:           in.JoinPayCallbackUrl,
		})
		if err != nil {
			return nil, err
		}
		logx.Infof("单笔代付响应：%+v", singlePayResp)

		if singlePayResp != nil {

			if singlePayResp.StatusCode == 2001 {
				// 汇聚成功受理请求后同步返回
				withdrawal.Status = 1
				withdrawal.UpdateTime = time.Now()
				withdrawal.UpdateBy = in.UpdateBy
				err = l.svcCtx.WalletWithdrawalModel.Update(l.ctx, withdrawal)
				if err != nil {
					return nil, err
				}
				return &walletClient.EmptyBody{}, nil
			}
			// 未成功受理
			return nil, errorx.NewDefaultError(fmt.Sprint(singlePayResp.Message, singlePayResp.Data.ErrorCode,
				singlePayResp.Data.ErrorDesc))
		}
		return nil, errorx.NewDefaultError(fmt.Sprint("调用第三方支付失败", err.Error()))
	}

	return nil, errorx.NewDefaultError("这条提现记录已处理，无需重复处理！")
}
